﻿/*
 * Created by SharpDevelop.
 * User: Intel
 * Date: 11.12.2014
 * Time: 10:23
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.Linq;
using Region.Utils;
using System.Linq;
namespace Invent
{
  /// <summary>
  /// Description of PlaceEdit.
  /// </summary>
  public partial class PlaceEdit : Form
  {		
    DatabaseInvent m_db;
    Guid m_PlaceUID;
    bool m_new = false;
    DataRow getRow(){ return (from d in m_db.Places.AsEnumerable() where d.Field<Guid>("PlaceUID")==m_PlaceUID select d).Single();}
    void ShowSelectors()
    {
		Guid iParentPlaceUID = Guid.Empty;
		var siParentPlace = ParentPlaceUID.SelectedItem as ListItemValue;
		if (siParentPlace != null) iParentPlaceUID = (Guid)siParentPlace.Value;		
    	ParentPlaceUID.Items.Clear();
		ParentPlaceUID.Items.Add(new ListItemValue(m_db.getPlaceName(Guid.Empty),Guid.Empty));
		foreach(var r in from row in m_db.Places.AsEnumerable() where row.Field<Guid>("PlaceUID")!=m_PlaceUID select row)
		{
			Guid PUID = r.Field<Guid>("PlaceUID");
			ParentPlaceUID.Items.Add(new ListItemValue(m_db.getPlaceName(PUID),PUID));
		}
		ParentPlaceUID.SelectedItem = new ListItemValue(m_db.getPlaceName(iParentPlaceUID),iParentPlaceUID);		
    }
	public PlaceEdit(DatabaseInvent db,Guid PlaceUID)
	{
		m_db = db;
		m_PlaceUID = PlaceUID;
		if (m_PlaceUID == Guid.Empty)
		{
		  DataRow row = m_db.newPlace("Наименование",Guid.Empty);
		  m_PlaceUID = row.Field<Guid>("PlaceUID");
		  m_new = true;
		}
      //
      // The InitializeComponent() call is required for Windows Forms designer support.
      //
      InitializeComponent();
      ShowSelectors();
      m_db.control_read(this,getRow());
    }
    void Button1Click(object sender, EventArgs e)
    {
      m_new = false;
      m_db.control_write(this,getRow());
      Close();
    }
    void Button2Click(object sender, EventArgs e)
    {
      if (m_new)
        m_db.deletePlace(m_PlaceUID);// Удалить если новый не сохранили
      Close();
    }
    void Button3Click(object sender, EventArgs e)
    {
      m_db.deletePlace(m_PlaceUID);
      Close();
    }
    void PlaceEditFormClosed(object sender, FormClosedEventArgs e)
    {
      if (m_new)
        m_db.deletePlace(m_PlaceUID);// Удалить если новый не сохранили
    }
  }
}
